/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-26 15:50:29
 * @LastEditTime: 2020-08-19 11:28:13
 * @LastEditors: Please set LastEditors
 */
import axios from 'axios'

import qs from 'qs'

import vue from '@/main.js'


const instance = axios.create({
  baseURL: '', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// 判断是否是FormData对象的方法
let isFormData = (v) => {
  return Object.prototype.toString.call(v) === '[object FormData]';
}

// 请求拦截器
instance.interceptors.request.use(
  config => {
    //判断是否登录
    if (window.localStorage.getItem("token")) {
      config.headers['X-Requested-With'] = 'xmlhttprequest';
      config.headers['application'] = 'app';
      config.headers['token'] = window.localStorage.getItem("token")
    }
    // 判断是否为post请求
    if (config.method.toLowerCase() == 'post') {
      console.log('config', config);
      config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
      // config.headers['content-type'] = 'application/json;charset=UTF-8';
      // 如果post传输数据,判断是不是formdata
      if (config.data) {
        // formdata请求
        if (isFormData(config.data)) {
          // config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        } else {
          // 不是formdata
          config.data = qs.stringify(config.data,{ arrayFormat: 'repeat', allowDots: true });
        }
      }
    }
    // console.log('config', config);
    return config;
  },
  error => {
    console.log(error) //
    return Promise.reject(error)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  response => {
    const res = response;
    // 响应状态判断0为成功
    if (res.data.code !== 1) {
      //关闭loading
      // 开启提示错误
      if (res.data.msg) {
        vue.$toast({
          message: res.data.msg,
          duration: 2000
        })
      }
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    //关闭loading
    if (error.response.status == 401) {
      vue.$toast({
        message: '登录失效，请重新登录',
        duration: 1000
      })
      vue.$router.push("/login")
    } else if (error.response.status == 500) {
      vue.$toast({
        message: '请求出现错误，请重试',
        duration: 1000
      })
    }
    // 跳转404
    else {
      // vue.$router.push("/notfound")
    }
    // 开启提示错误
    return Promise.reject(error)
  }
)

// 兼容get请求方式的data/params传参
function http(config) {
    // 在axios中 对get和post请求处理参数的方式不同
    if (config.method === 'get' && config.data) {
        // config.data = qs.stringify(config.data, { arrayFormat: 'repeat', allowDots: true });
        config.params = config.data;
    }
    return instance(config);
}

export default http
